//
//  MDFModelCreate.m
//  ModelCreate
//
//  Created by tanxk_mini on 2018/11/19.
//  Copyright © 2018 runzezhihun. All rights reserved.
//

#import "MDFModelCreate.h"
#import "MDFModelCreateStatus.h"

@interface MDFModelCreate ()

@property (nonatomic, strong) NSMutableString *methodsHString;
@property (nonatomic, strong) NSMutableString *methodsMString;
@property (nonatomic, strong) NSArray <NSString *>*methodsImportString;

@end

@implementation MDFModelCreate

+ (MDFModelCreate *)shared {
    static id sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (BOOL)createFolder:(NSString *)path {
    
    NSString * dataFilePath = path;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL success = [fileManager createDirectoryAtPath:dataFilePath withIntermediateDirectories:YES attributes:nil error:nil];
    return success;
}

- (BOOL)createModelFileH:(NSString *)fileName {
    
    NSString *filePath = [NSString stringWithFormat:@"%@%@",self.hostPath,obtionModelFileH(fileName)];
    
    NSString *className = obtionModelFile(fileName);
    NSString *superName = @"MDFBaseRequest";
    NSString *content = @"- (instancetype)initWithParam:(NSMutableDictionary *)param;";
    NSArray <NSString *> *imports = @[obtionItemFile(fileName)];
    
    NSMutableString *testString = obtioFileToInterface(className, superName, content, imports);
    
    BOOL success = NO;
    success = [testString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    return success;
}

- (BOOL)createModelFileM:(NSString *)fileName array:(NSArray *)array{
    
    NSString *filePath = [NSString stringWithFormat:@"%@%@",self.hostPath,obtionModelFileM(fileName)];
    
    NSString *contentString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    if (contentString) {
        NSLog(@"文件存在不需要更新%@.m",fileName);
        return NO;
    }
    
    NSString *className = obtionModelFile(fileName);
    NSString *content_h = @"@property (nonatomic, strong) NSMutableDictionary *param;";
    
    NSMutableString *content_m = [NSMutableString string];
    [content_m appendFormat:@"- (instancetype)initWithParam:(NSMutableDictionary *)param { \
     \n\n \
     self = [super init]; \
     \n\n \
     if (self) { \n \
         self.param = [NSMutableDictionary dictionaryWithDictionary:param]; \n \
         self.isAutoShowLoading = YES; \n \
         self.isAutoShowBusinessErrorToast = YES; \n \
         self.parseCls = [%@ class]; \n \
     } \n \
     return self;\n} \
     \n\n",obtionItemFile(fileName)];
    [content_m appendFormat:@"- (NSString *)requestUrl { \n \
     return K%@Address; \n}\n",[fileName capitalizedString]];
    [content_m appendString:@"\n"];
    [content_m appendString:@"- (YTKRequestMethod)requestMethod { \n \
     return YTKRequestMethodPOST;\n}\n"];
    [content_m appendString:@"\n"];
    [content_m appendString:@"- (id)requestArgument { \n \
     return self.param; \n}\n"];
    [content_m appendString:[self obtionMethod:fileName array:array]];
    
    NSMutableString *testString = obtioFileToImplementationAndInterface(className, content_h, content_m, nil);
    
    return [testString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];;
}

- (BOOL)createItemFileH:(NSString *)fileName dict:(NSDictionary *)dict {
    
    NSString *filePath = [NSString stringWithFormat:@"%@%@",self.hostPath,obtionItemFileH(fileName)];
    NSString *className = obtionItemFile(fileName);
    NSString *superName = @"MDFBaseRequestItem";
    NSString *content = [self mdf_creatPropertyCodeWith:dict];
    
    NSMutableString *string = obtioFileToInterface(className, superName, content, nil);
    
    NSString *contentString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    
    if (contentString && [contentString containsString:@"///custom"]) {
        NSLog(@"文件存在且存在自定义字段，去修改：%@.h",className);
        // 获取文件自定义字段的位置
        NSRange startCustomRange = [contentString rangeOfString:@"///custom"];
        NSRange endCustomRange = [contentString rangeOfString:@"@end"];
        
        //需要减去 \n 这几个字符的位置，所以进行+2操作
        startCustomRange.length = endCustomRange.location - (startCustomRange.location + 2);
        
        NSString *customProperty = [NSString stringWithFormat:@"\n%@\n",[contentString substringWithRange:startCustomRange]];
        
        NSRange endCustomRange2 = [string rangeOfString:@"@end"];
        [string insertString:customProperty atIndex:endCustomRange2.location-1];
    }
    return [string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];;
}

- (BOOL)createItemFileM:(NSString *)fileName {
    
    NSString *filePath = [NSString stringWithFormat:@"%@%@",self.hostPath,obtionItemFileM(fileName)];
    NSString *className = obtionItemFile(fileName);
    NSMutableString *testString = obtioFileToImplementation(className, nil, YES);;
    
    NSString *contentString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    if (contentString && contentString.length) {
        return NO;
    } else {
        return [testString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
}

- (BOOL)createPortFileM:(NSString *)fileName string:(NSString *)info{
    
    NSString *filePath = [NSString stringWithFormat:@"%@%@",self.hostPath,obtionPortFile(fileName)];
    
    NSMutableString *testString = [NSMutableString stringWithFormat:@"#ifndef %@\n",obtionPortFileH(fileName)];
    [testString appendFormat:@"#define %@\n",obtionPortFileH(fileName)];
    [testString appendString:@"\n"];
    [testString appendString:@"#import <Foundation/Foundation.h>\n"];
    [testString appendString:info];
    [testString appendString:@"\n"];
    [testString appendFormat:@"#endif /* %@ */",obtionPortFileH(fileName)];
    
    return [testString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

- (BOOL)createtestvcH:(NSString *)fileName {
    
    NSString *filePath = [NSString stringWithFormat:@"%@%@",self.hostPath,[NSString stringWithFormat:@"CDK%@.h",fileName]];
    
    NSString *className = [NSString stringWithFormat:@"CDK%@",fileName];;
    NSString *content = self.methodsHString;
    NSArray <NSString *> *imports = @[@"UIKit/UIKit"];
    
    NSMutableString *string = obtioFileToInterface(className, nil, content, imports);
    return [string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];;
}

- (BOOL)createtestvcM:(NSString *)fileName {
    
    NSString *filePath = [NSString stringWithFormat:@"%@%@",self.hostPath,[NSString stringWithFormat:@"CDK%@.m",fileName]];
    
    NSString *className = [NSString stringWithFormat:@"CDK%@",fileName];
    NSString *content = self.methodsMString;
    
    NSMutableString *string = obtioFileToImplementationAndInterface(className, nil, content, self.methodsImportString);
    return [string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];;
}

#pragma mark - 辅助方法

- (void)setMethodsImportString:(NSArray<NSString *> *)methodsImportString {
    _methodsImportString = methodsImportString;
}

- (NSString *)mdf_creatPropertyCodeWith:(NSDictionary *)dict {
    
    NSMutableString *strM = [NSMutableString string];
    
    [dict  enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull propertyName, id  _Nonnull value, BOOL * _Nonnull stop) {
        NSString *code;
        
        NSString *propertyType = [value componentsSeparatedByString:@""].lastObject;
        NSString *descriptionString = [value componentsSeparatedByString:@""].firstObject;
        
        if ([propertyName isEqualToString:@"code"] || [propertyName isEqualToString:@"message"] || [propertyName isEqualToString:@"resultObj"] || [propertyName isEqualToString:@"timestamp"]) {
            return ;
        }
        
        if ([propertyType isEqualToString:@"array"]) {
            code=[NSString stringWithFormat:@"@property (nonatomic,strong) NSArray  *%@; ///< %@",propertyName,descriptionString];
        } else if ([propertyType isEqualToString:@"string"]) {
            code=[NSString stringWithFormat:@"@property (nonatomic,strong) NSString *%@; ///< %@",propertyName,descriptionString];
        } else if ([propertyType isEqualToString:@"integer"]) {
            code=[NSString stringWithFormat:@"@property (nonatomic,strong) NSString *%@; ///< %@",propertyName,descriptionString];
        } else if ([propertyType isEqualToString:@"number"]) {
            code=[NSString stringWithFormat:@"@property (nonatomic,strong) NSNumber *%@; ///< %@",propertyName,descriptionString];
        } else if ([propertyType isEqualToString:@"object"]) {
            code=[NSString stringWithFormat:@"@property (nonatomic,strong) NSDictionary *%@; ///< %@",propertyName,descriptionString];
        } else if ([propertyType isEqualToString:@"boolean"]) {
            code=[NSString stringWithFormat:@"@property (nonatomic,assign) BOOL      %@; ///< %@",propertyName,descriptionString];
        } else {
            NSLog(@"解析不了的类型，需要添加");
            NSAssert(value, @"这是什么鬼");
            code=[NSString stringWithFormat:@"@property (nonatomic,strong) NSString *%@; ///< %@",propertyName,descriptionString];
        }
        [strM appendFormat:@"\n%@",code];
    }];
//    NSLog(@"%@",strM);
    return strM;
}

/// < 生成请求方法
- (NSString *)obtionMethod:(NSString *)name array:(NSArray *)array {
    
    NSMutableString *string = [NSMutableString string];
    [string appendString:@"\n"];
    [string appendFormat:@"- (void)handleDataTo%@ {\n",[name capitalizedString]];
    [string appendString:@"\n"];
    [string appendString:@"    NSMutableDictionary *params = [NSMutableDictionary new];\n"];
    
    [array enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [string appendFormat:@"    params[@\"%@\"] = @\"%@\";",obj[@"name"],obj[@"description"]];
        [string appendString:@"\n"];
    }];
    [string appendString:@"\n"];
    [string appendFormat:@"    [[[%@ alloc] initWithParam:params] startWithCompletionBlockWithSuccess:^(__kindof %@ *item) {",obtionModelFile(name),obtionItemFile(name)];
    [string appendString:@"\n\n"];
    [string appendString:@"        NSLog(@\"%@\",item);"];
    [string appendString:@"\n\n"];
    [string appendString:@"    } failure:^(__kindof NSError *error) {"];
    [string appendString:@"\n\n"];
    [string appendString:@"    }];"];
    [string appendString:@"\n"];
    [string appendString:@"}"];
    [string appendString:@"\n"];
    
    [self.methodsHString appendString:[NSString stringWithFormat:@"\n- (void)handleDataTo%@;\n",[name capitalizedString]]];
    [self.methodsMString appendString:[self obtionMethod2:name array:array]];
    
    return string;
}

/// < 生成请求方法
- (NSMutableString *)obtionMethod2:(NSString *)name array:(NSArray *)array {
    
    NSMutableString *string = [NSMutableString string];
    [string appendString:@"\n"];
    [string appendFormat:@"- (void)handleDataTo%@ {\n",[name capitalizedString]];
    [string appendString:@"\n"];
    [string appendString:@"    NSMutableDictionary *params = [NSMutableDictionary new];\n"];
    
    [array enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [string appendFormat:@"    params[@\"%@\"] = @\"%@\";",obj[@"name"],obj[@"description"]];
    }];
    [string appendString:@"\n\n"];
    [string appendFormat:@"    [[[%@ alloc] initWithParam:params] startWithCompletionBlockWithSuccess:^(__kindof %@ *item) {",obtionModelFile(name),obtionItemFile(name)];
    [string appendString:@"\n\n"];
    
    [string appendString:@"        NSMutableString *string = [NSMutableString string];"];
    [string appendString:@"\n"];
    [string appendString:@"        [string appendFormat:@\"params:%@\",params];"];
    [string appendString:@"\n"];
    [string appendString:@"        [string appendFormat:@\"response:%@\",item.responseObject];"];
    [string appendString:@"\n"];
    [string appendFormat:@"        [BaseAlertManager alertWithTitle:@\"%@\" message:string Cancel:nil Confirm:nil];",name];
    [string appendString:@"\n\n"];
    
    [string appendString:@"    } failure:^(__kindof NSError *error) {"];
    [string appendString:@"\n\n"];
    
    [string appendString:@"        NSMutableString *string = [NSMutableString string];"];
    [string appendString:@"\n"];
    [string appendString:@"        [string appendFormat:@\"params:%@\",params];"];
    [string appendString:@"\n"];
    [string appendString:@"        [string appendFormat:@\"error:%@\",error];"];
    [string appendString:@"\n"];
    [string appendString:@"        [SVProgressHUD dismiss];"];
    [string appendString:@"\n"];
    [string appendFormat:@"        [BaseAlertManager alertWithTitle:@\"%@\" message:string Cancel:nil Confirm:nil];",name];
    [string appendString:@"\n\n"];
    
    [string appendString:@"    }];"];
    [string appendString:@"\n"];
    [string appendString:@"}"];
    [string appendString:@"\n"];
    
    return string;
}

- (NSMutableString *)methodsHString {
    
    if (!_methodsHString) {
        _methodsHString = [NSMutableString string];
    }
    return _methodsHString;
}

- (NSMutableString *)methodsMString {
    
    if (!_methodsMString) {
        _methodsMString = [NSMutableString string];
    }
    return _methodsMString;
}
@end
